package com.example.stars_project_android.register;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.text.method.TransformationMethod;
import android.text.style.MaskFilterSpan;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.stars_project_android.HelloActivity;
import com.example.stars_project_android.R;
import com.example.stars_project_android.util.Constant;
import com.mob.MobSDK;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class Register extends AppCompatActivity implements View.OnClickListener {

    public static final String TAG = "Register";
    private EditText editPhone, editCode, editPsd, editRePsd; //手机号，验证码，密码，确认密码
    private ImageView eye, reEye;  //密码的眼睛，确认密码的眼睛
    private Button btnRegister,btnGetCode;  //立即注册的按钮
    private Timer timer;
    //倒计时60秒
    private int count = Constant.MESSAGE_COUNTDOWNTIME; //短信验证码发送倒计时
    private boolean isHide = false;  //输入框密码是否是隐藏，默认为false
    private int code;   //返回的状态码
    private String msgCon;  //返回的错误信息
    public static final int RESEND = 1, SEND = 2, SUCCESS = 3, CODEFALSE = 4, FALSE = 5;  //常量值

    private Handler myHandler = new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            //处理子线程发送的消息
            String result = (String) msg.obj;
            try {
                JSONObject jsonObject = new JSONObject(result);
                code = jsonObject.getInt("code");
                msgCon = jsonObject.getString("msg");
                Log.e("状态码",code+"");
                Log.e("返回的提示信息：",msgCon);
                if (code == 200){
                    JSONObject jsonObject1 = jsonObject.getJSONObject("date");
                    Constant.userId = jsonObject1.getString("userId");
                    Constant.starName = jsonObject1.getString("starName");
                    Constant.longitude = jsonObject1.getString("longitude");
                    Constant.latitude = jsonObject1.getString("latitude");
                    Constant.distance = jsonObject1.getInt("distance");
                    Constant.registerTime = jsonObject1.getString("registerTime");
                    //跳转到欢迎界面
                    Intent intent = new Intent(Register.this, HelloActivity.class);
                    startActivity(intent);
                } else {
                    Toast.makeText(Register.this,msgCon,Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };


    /**
     * 短信验证码业务的EventHandler
     * @reslut 请求结果返回码
     * @event 验证码返回码（不是验证码，是结果码，判断验证码是否成功发送，是否一致等）
     */
    private EventHandler handler = new EventHandler() {
        @Override
        // 该方法是在子线程执行，如果要更新UI，就是线程间的通信
        public void afterEvent(int event, int result, Object data) {
            super.afterEvent(event, result, data);
            Message msg = new Message();
            if(result == SMSSDK.RESULT_COMPLETE) {
                //回调成功
                if(event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                    // 验证码发送成功，手机将接收到验证码
                    msg.what = SEND;
                }else if(event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                    // 验证码提交成功，即验证成功
                    msg.what = SUCCESS;
                }else {
                    // 验证失败
                    msg.what = CODEFALSE;
                }
                UIHandler.sendMessage(msg);
            }else if(result == SMSSDK.RESULT_ERROR) {
                // 回调失败，日志输出错误信息
                msg.what = FALSE;
                ((Throwable) data).printStackTrace();
                UIHandler.sendMessage(msg);
            }
        }
    };

    private Handler UIHandler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                // 定时任务消息
                case RESEND:
                    if(msg.arg1 == RESEND) {
                        btnGetCode.setText("重新获取验证码");
                        count = 60;
                        timer.cancel();
                        btnGetCode.setEnabled(true);
                    }else {
                        btnGetCode.setText(count + "");
                    }
                    break;
                case SEND:
                    Toast.makeText(Register.this,"验证码已发送",Toast.LENGTH_SHORT).show();
                    break;
                case SUCCESS:
                    Toast.makeText(Register.this, "验证成功", Toast.LENGTH_SHORT).show();
                    //获取网络连接
                    getConn();
                    break;
                case CODEFALSE:
                    Toast.makeText(Register.this, "验证码错误，请稍后重试", Toast.LENGTH_SHORT).show();
                    break;
                case FALSE:
                    Toast.makeText(Register.this, "无法获取，请稍后重试", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        MobSDK.init(Register.this);
        MobSDK.submitPolicyGrantResult(true);

        //如果 targetSdkVersion小于或等于22，可以忽略这一步，如果大于或等于23，需要做权限的动态申请：
        if (Build.VERSION.SDK_INT >= 23) {
            String[] mPermissionList = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.CALL_PHONE, Manifest.permission.READ_LOGS, Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.SET_DEBUG_APP, Manifest.permission.SYSTEM_ALERT_WINDOW, Manifest.permission.GET_ACCOUNTS, Manifest.permission.WRITE_APN_SETTINGS};
            ActivityCompat.requestPermissions(this, mPermissionList, 123);
        }
        //设置属性
        setView();
        //注册回调监听接口
        SMSSDK.registerEventHandler(handler);
    }

    /**
     * 属性
     */
    private void setView() {
        editPhone = findViewById(R.id.edit_phone);
        editCode = findViewById(R.id.edit_code);
        editPsd = findViewById(R.id.edit_psd);
        editRePsd = findViewById(R.id.edit_rePsd);
        btnGetCode = findViewById(R.id.btn_get_code);
        btnGetCode.setOnClickListener(this);
        btnRegister = findViewById(R.id.btn_register);
        btnRegister.setOnClickListener(this);
        eye = findViewById(R.id.eye);
        eye.setOnClickListener(this);
        reEye = findViewById(R.id.reEye);
        reEye.setOnClickListener(this);
    }

    /**
     * 点击眼睛图标显示密码明文或密文
     */
    private void isShowPassword(EditText editText) {
        if(isHide == false) {
            //R.mipmap.password_show是表示显示密码的“眼睛”图标
            if (editText == editPsd){
                eye.setImageResource(R.mipmap.password_show);
                //密文
                HideReturnsTransformationMethod method1 = HideReturnsTransformationMethod.getInstance();
                editText.setTransformationMethod(method1);
                isHide = true;
            } else {
                reEye.setImageResource(R.mipmap.password_show);
                //密文
                HideReturnsTransformationMethod method1 = HideReturnsTransformationMethod.getInstance();
                editText.setTransformationMethod(method1);
                isHide = true;
            }
        } else {
            if (editText == editPsd){
                eye.setImageResource(R.mipmap.password_miss);
                //密文
                TransformationMethod method2 = PasswordTransformationMethod.getInstance();
                editText.setTransformationMethod(method2);
                isHide = false;
            } else {
                //R.mipmap.password_miss是表示隐藏密码的“眼睛+斜杠”图标
                reEye.setImageResource(R.mipmap.password_miss);
                //密文
                TransformationMethod method2 = PasswordTransformationMethod.getInstance();
                editText.setTransformationMethod(method2);
                isHide = false;
            }

        }
        //重置光标位置
        int index = editText.getText().toString().length();
        editText.setSelection(index) ;
    }

    /**
     * 定时任务
     */
    private void setTimer() {
        // 设置按钮不可点击
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Message message = new Message();
                // 根据自己需要更改id
                message.what = 1;
                message.arg1 = count;
                if(count != 0) {
                    count--;
                }else {
                    return;
                }
                //线程通信，Handler.sendMessage();
                UIHandler.sendMessage(message);
            }
        },1000,1000);
    }

    // 使用完EventHandler需注销，防止内存泄露
    @Override
    protected  void onDestroy() {
        super.onDestroy();
        SMSSDK.unregisterEventHandler(handler);
    }

    /**
     * 获取网络连接
     */
    private void getConn() {
        //向后端传递页面上获取的手机号和密码。
        //将数据封装
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("phoneNumber",editPhone.getText().toString());
            Constant.phone = editPhone.getText().toString();
            jsonObject.put("userPsd",editPsd.getText().toString());
            Log.e("phone",editPhone.getText().toString());
            Log.e("password",editPsd.getText().toString());
            Log.e("json格式",jsonObject.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        MediaType type = MediaType.parse("application/json;charset=utf-8");
        RequestBody requestBody = RequestBody.create(type,""+jsonObject.toString());

        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://192.168.1.7:8080/userInfo/register")
                .post(requestBody)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("okhttp","请求失败");
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //处理接收到的数据
                Log.e("okhttp","请求成功");
                String str = response.body().string();
                Log.e("返回的数据",str);
                //数据源发送改变，需要更新界面，使用Handler
                Message message = new Message();
                message.obj = str;
                myHandler.sendMessage(message);//发送到主线程的消息队列
            }
        });
    }

    @Override
    public void onClick(View v) {
        String phoneNum = editPhone.getText().toString();
        switch (v.getId()){
            case R.id.btn_get_code:
                // 1. 判断手机号是不是11位并且看格式是否合理
                if (!judgePhoneNums(phoneNum)){
                    return;
                }
                //点击获取验证码
                SMSSDK.getVerificationCode("86",phoneNum);
                setTimer();
                break;
            case R.id.btn_register:
                //点击注册
                SMSSDK.submitVerificationCode("86",phoneNum,editCode.getText().toString());
                break;
            case R.id.eye:
                isShowPassword(editPsd);
                break;
            case R.id.reEye:
                isShowPassword(editRePsd);
                break;
            default:
                break;
        }
    }

    /**
     * 判断手机号码是否合理
     *
     * @param phoneNums
     */
    private boolean judgePhoneNums(String phoneNums) {
        if (isMatchLength(phoneNums, 11)
                && isMobileNO(phoneNums)) {
            return true;
        }
        Toast.makeText(this, "手机号码输入有误！", Toast.LENGTH_SHORT).show();
        return false;
    }

    /**
     * 判断一个字符串的位数
     *
     * @param str
     * @param length
     * @return
     */
    public static boolean isMatchLength(String str, int length) {
        if (str.isEmpty()) {
            return false;
        } else {
            return str.length() == length ? true : false;
        }
    }

    /**
     * 验证手机格式
     */
    public static boolean isMobileNO(String mobileNums) {
        /*
         * 移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
         * 联通：130、131、132、152、155、156、185、186 电信：133、153、180、189、（1349卫通）
         * 总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9
         */
        String telRegex = "[1][358]\\d{9}";// "[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (TextUtils.isEmpty(mobileNums))
            return false;
        else
            return mobileNums.matches(telRegex);
    }

}